import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/models/package_group.dart';
import 'package:boss/models/packing_data.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class PackageProvider extends ChangeNotifier {
  PackingData data;

  Future<Result<PackingData>> initData() async {
    try {
      var res = await api.queryPacking();
      if (!res.successful()) {
        return Result.error(res.msg);
      }

      data = res.data;
      data.targetValue = 1;

      notifyListeners();

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  setCommoditys(List<Commodity> commoditys) {
    data.commodityFormList = commoditys
        .map((item) => CommodityFormList.fromJson({
              'commodityId': item.id,
              'commodityName': item.title,
              'price': item.price,
              'skuId': item.sku?.skuId,
              'skuName': item.sku?.skuName,
              'unit': item.unit,
            }))
        .toList();
  }

  setPackingFee(String price) {
    data.costAmount = AmountUtil.string2Price(price);
  }

  update() async {
    if (data.costAmount == null) {
      toast('请填写完整的规则');
      return;
    }

    try {
      showLoadingToast();
      var res = await api.updatePacking(data);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('修改成功');
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }
}
